package com.winz.cultureapp.fragment;

import android.content.Intent;
import android.net.Uri;

import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mine.xrecyclerview.XRecyclerView;
import com.mine.xrecyclerview.rcvadapter.OnItemClickListener;
import com.winz.cultureapp.R;
import com.winz.cultureapp.adapter.xrcv.ActivityDataAdapter;
import com.winz.cultureapp.base.BaseFragment;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.ActivityBannertBean;
import com.winz.cultureapp.entity.ActivityListBean;
import com.winz.cultureapp.entity.UserInfoBean;
import com.winz.cultureapp.filter.activity.CsPopupWindow;
import com.winz.cultureapp.filter.activity.LocationPopupWindow;
import com.winz.cultureapp.filter.activity.PxPopupWindow;
import com.winz.cultureapp.filter.activity.XxPopupWindow;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.request.UserCollectionReq;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.SharePrefsUtil;
import com.winz.filterbar.FilterBar;
import com.winz.filterbar.FilterTab;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 文化活动
 */
public class ActivityFragment extends BaseFragment implements XRecyclerView.LoadingListener, OnItemClickListener, FilterBar.SelectedMenuListener, ActivityDataAdapter.OnAddOrCancelListener {
    @BindView(R.id.fl_back)
    public FrameLayout mFl_back;
    @BindView(R.id.tv_top_title)
    public TextView mTv_top_title;

    @BindView(R.id.xrcv_activity)
    public XRecyclerView mXrcv_activity;
    @BindView(R.id.fb_activity)
    public FilterBar mFb_activity;

    private boolean isRefresh = true;
    private int limit = 10;
    private int page = 1;
    private int totalPage = 0;

    private String unitId = "0"; // 单位ID
    private String areaId = "0"; // 区域ID
    private String categoryId = "0"; // 分类ID
    private String sort = "0"; // 0默认1人气最高2最新发布


    private List<ActivityListBean.DataBean.ListBean> mDatas;
    private ActivityDataAdapter mAdapter;

    private List<ActivityBannertBean.DataBean.ListBean> mDatas_banner;
    private List<Integer> images = new ArrayList<>();
    private List<String> titles = new ArrayList<>();

    private Map<FilterTab,PopupWindow> map_pop = new HashMap<>();

    private LocationPopupWindow mPop_location;
    private CsPopupWindow mPop_cs;
    private PxPopupWindow mPop_px;
    private XxPopupWindow mPop_xx;

    @Override
    protected int contentView() {
        return R.layout.fragment_activity;
    }

    public static ActivityFragment getInstance(){
        ActivityFragment fragment = new ActivityFragment();

        return fragment;
    }

    @Override
    protected void initViews(View view) {
        mDatas = new ArrayList<>();
        mDatas_banner = new ArrayList<>();
        images = new ArrayList<>();
        titles = new ArrayList<>();

        mTv_top_title.setText(getString(R.string.activity_top_title));
//        mIv_right.setImageResource(R.drawable.icon_center);
        mFl_back.setVisibility(View.GONE);


        // XrecyclerView
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        mXrcv_activity.setLayoutManager(manager);
        mXrcv_activity.setPullRefreshEnabled(true);
        mXrcv_activity.setLoadingMoreEnabled(true);

        mXrcv_activity.setFocusable(false);
        mXrcv_activity.setFocusableInTouchMode(false);

        mAdapter = new ActivityDataAdapter(mContext,mDatas,R.layout.empty_view,R.layout.item_home_list);

        // 初始化
        mPop_location = new LocationPopupWindow(mContext,mFb_activity.getTabs().get(0));
        map_pop.put(mFb_activity.getTabs().get(0),mPop_location);
        mPop_cs = new CsPopupWindow(mContext,mFb_activity.getTabs().get(1));
        map_pop.put(mFb_activity.getTabs().get(1), mPop_cs);
        mPop_px = new PxPopupWindow(mContext,mFb_activity.getTabs().get(2));
        map_pop.put(mFb_activity.getTabs().get(2), mPop_px);
        mPop_xx = new XxPopupWindow(mContext,mFb_activity.getTabs().get(3));
        map_pop.put(mFb_activity.getTabs().get(3), mPop_xx);

    }

    @Override
    protected void initEvents() {
        mXrcv_activity.setAdapter(mAdapter);
        mXrcv_activity.setLoadingListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnAddOrCancelListener(this);

        mFb_activity.setSelectedMenuListener(this);

        /* 区域 */
        mPop_location.setOnFinishListener(new LocationPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    areaId = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_location.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPop_location.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

        /* 分类 */
        mPop_cs.setOnFinishListener(new CsPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    categoryId = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_cs.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPop_cs.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

        /* 筛选 */
        mPop_xx.setOnFinishListener(new XxPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    unitId = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_xx.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPop_xx.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

        /* 排序 */
        mPop_px.setOnFinishListener(new PxPopupWindow.OnFinishListener() {
            @Override
            public void onFinish(FilterTab flag, String data) {
                flag.setText(data.split(",")[0]);
                map_pop.get(flag).dismiss();
                if (data.split(",").length>1){
                    sort = data.split(",")[1];
                    getList();
                }
            }
        });
        mPop_px.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                mFb_activity.getTabSelectedObervable();
                mPop_px.getFlag().setFilterTabSelected(false,FilterTab.FLAG_OTHER);
            }
        });

    }

    @Override
    protected void loadDatas() {
        getList();
    }

    /**
     * 获取数据列表
     */
    private void getList() {
        showProgressDialog();

        HttpUitls.onGet("activity", RequestFactory.getInstance().activity(page +"",limit+"",unitId + "",areaId,categoryId,sort+ ""), new OnResponeListener<ActivityListBean>() {
            @Override
            public void onSuccess(ActivityListBean bean) {
                Logger.d("activity==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
//                            totalPage = bean.data.totalPage;
                    if (bean.data.list != null && bean.data.list.size() > 0) {
                        mXrcv_activity.setLoadingMoreEnabled(true);
                        if (isRefresh) {
                            mDatas.clear();
                            mDatas = bean.data.list;
                        } else {
                            mDatas.addAll(bean.data.list);
                        }
                    } else {
                        mDatas.clear();
                        ActivityListBean.DataBean.ListBean empty = new ActivityListBean.DataBean.ListBean();
                        empty.layout_type = -1;
                        mDatas.add(empty);
                        mXrcv_activity.setLoadingMoreEnabled(false);
                    }
                    mAdapter.setDatas(mDatas);
                } else {
                    showMsg(bean.msg);
                }
                if (isRefresh) {
                    mXrcv_activity.refreshComplete();
                } else {
                    mXrcv_activity.loadMoreComplete();
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d("activity==>>", error);
                if (isRefresh) {
                    mXrcv_activity.refreshComplete();
                } else {
                    mXrcv_activity.loadMoreComplete();
                }
            }
        });
    }

    @OnClick({R.id.rl_right})
    public void knife(View view){
        switch (view.getId()){
            case R.id.rl_right:
                showMsg("开发中");
                break;
        }
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        loadDatas();
    }

    /**
     * 加载
     */
    @Override
    public void onLoadMore() {
        isRefresh = false;
        if (page>=totalPage){
            mXrcv_activity.setNoMore(true,true,"没有更多数据了");
        }else {
            page++;
            loadDatas();
        }
    }

    /**
     * item点击事件
     * @param parent
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(ViewGroup parent, View view, int position) {
//        Bundle bundle = new Bundle();
////        bundle.putSerializable(Constants.KEY.ACTIVITY.DATA, mDatas.get(position));
//        bundle.putSerializable(Constants.KEY.ACTIVITY.ITEM_ID, mDatas.get(position).activityId);
//        bundle.putString(Constants.KEY.ACTIVITY.ITEM_DES_HREF,Constants.URL.IP + "/activity/detail/" + mDatas.get(position).activityId);
//
//        startActivity(ActvitiyDesActivity.class,false,bundle);

        Uri uri = Uri.parse(Constants.URL.IP + "/activity/detail/" + mDatas.get(position).activityId);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(ViewGroup parent, View view, int position) {
        return false;
    }

    /**
     * 选择筛选项
     */
    @Override
    public void onSelectedMenu(FilterTab view, boolean selected) {
        // 打开或者关闭筛选弹窗
        if (selected){
            map_pop.get(view).showAsDropDown(view);
        }else {
            map_pop.get(view).dismiss();
        }

    }


    /**
     * 收藏
     * @param position
     */
    @Override
    public void onAddOrCancel(int position) {
        showProgressDialog();

        HttpUitls.onPostByToken(mDatas.get(position).collectionStatus == 0 ? "user_collection_save" : "user_collection_cancel",
                SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN),
                new UserCollectionReq(mDatas.get(position).activityId, "1"),
                new OnResponeListener<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean bean) {
                Logger.d(mDatas.get(position).collectionStatus == 0 ? "user_collection_save" : "user_collection_cancel" + "==>>", JsonUtil.getJsonFromObj(bean));
                HttpUitls.isExpire(bean.code);
                if (bean.code == 0) {
                    showMsg("收藏成功");
                    mDatas.get(position).collectionStatus = mDatas.get(position).collectionStatus == 0 ? 1 : 0;
                    mAdapter.setDatas(mDatas);
                } else {
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                dismissProgressDialog();
                Logger.d(mDatas.get(position).collectionStatus == 0 ? "user_collection_save" : "user_collection_cancel" + "==>>", error);
            }
        });
    }
}
